package com.aurora.leetcode.answer;

import com.aurora.leetcode.util.MyUtils;

/**
 * @author : Aurora
 * @date : 4/12/24 5:04 AM
 * @description
 * 给你一个正整数 n ，生成一个包含 1 到 n^2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 */
public class GenerateMatrix_59 {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int count = 0;
        int i=0,j=0;
        int lowEdge = 0;
        int maxEdge = n-1;
        int mode=0;
        while(count < n*n){
            ++count;
            switch (mode){
                case 0:
                    result[i][j++] = count;
                    if (j>maxEdge)
                    {
                        j=maxEdge;
                        mode++;
                        ++i;
                    }
                    break;

                case 1:
                    result[i++][j] = count;
                    if (i>maxEdge)
                    {
                        i=maxEdge;
                        maxEdge--;
                        mode++;
                        --j;
                    }
                    break;
                case 2:
                    result[i][j--] = count;
                    if (j<lowEdge) {
                        j = lowEdge;
                        mode++;
                        lowEdge++;
                        --i;
                    }
                    break;
                case 3:
                    result[i--][j] = count;
                    if (i<lowEdge)
                    {
                        mode=0;
                        i=j=lowEdge;
                    }
                    break;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        GenerateMatrix_59 generateMatrix59 = new GenerateMatrix_59();
        int[][] ints = generateMatrix59.generateMatrix(4);
        MyUtils.printArray(ints);
    }
}
